

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=&#34;auto&#34;>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/blog/img/favicon.png">
  <link rel="icon" href="/blog/img/favicon.jpg">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="">
  <meta name="author" content="John Doe">
  <meta name="keywords" content="">
  
  <title>JavaScript笔记-BOM - ITaylorfan的小站</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/blog/lib/hint/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10.7.2/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css" />
  



<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_kmeydafke9r.css">


<link  rel="stylesheet" href="/blog/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"itaylorfan.gitee.io","root":"/blog/","version":"1.8.11","typing":{"enable":true,"typeSpeed":70,"cursorChar":"❤","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/blog/js/utils.js" ></script>
  <script  src="/blog/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.4.0"></head>


<body>
  <header style="height: 85vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/blog/">&nbsp;<strong>ITaylorfan</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" data-toggle="modal" data-target="#modalSearch">&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;</a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/blog/img/TS8-10-9.jpg') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="JavaScript笔记-BOM">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2021-09-29 18:59" pubdate>
        2021年9月29日 晚上
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      5k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      62
       分钟
    </span>
  

  
  
</div>

            
          </div>

          
            <div class="scroll-down-bar">
              <i class="iconfont icon-arrowdown"></i>
            </div>
          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">JavaScript笔记-BOM</h1>
            
            <div class="markdown-body">
              <h1 id="JavaScript-BOM"><a href="#JavaScript-BOM" class="headerlink" title="JavaScript-BOM"></a>JavaScript-BOM</h1><p>BOM的全称叫<code>Browser Object Model</code>浏览器编程，它主要是对浏览器的相关API进行操作与处理</p>
<h2 id="1-location"><a href="#1-location" class="headerlink" title="1.location"></a>1.location</h2><p>location指的是浏览器里面的地址栏</p>
<ol>
<li><p><code>hostname</code>代表当前网页的主机名</p>
</li>
<li><p><code>port</code>代表当前网页的端口号</p>
<p>http默认的端口号是80，https默认的端口号是443</p>
</li>
<li><p><code>host</code>代表当前网页的主机地址，它包含了<code>hostname</code>与<code>port</code></p>
</li>
<li><p><code>protocol</code>代表当前网页地址的协议，如<code>http/https</code></p>
</li>
<li><p><code>pathname</code>代表的是当前网页域后面的 <code>/</code>以后的东西</p>
<p><img src="https://pic.imgdb.cn/item/6146c5c72ab3f51d9162adc3.png" srcset="/blog/img/loading.gif" lazyload alt="image-20210918113202074"></p>
</li>
<li><p><code>origin</code>当代表当前是网站的<strong>域</strong>信息，它是由协议，主机名，端口号共同组成，如下</p>
<figure class="highlight awk"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs awk">http:<span class="hljs-regexp">//</span>www.softeem.xin<br>https:<span class="hljs-regexp">//</span>www.baidu.com<br>http:<span class="hljs-regexp">//</span>www.softeem.xin:<span class="hljs-number">8090</span><br>http:<span class="hljs-regexp">//</span><span class="hljs-number">127.0</span>.<span class="hljs-number">0.1</span>:<span class="hljs-number">5500</span><br></code></pre></td></tr></table></figure>

<blockquote>
<p>这是一个非常重要的东西，后期的Ajax，本地存储，会话存储，cookie还有其它的一些操作都会使用到这个origin，还会演变出一个技术叫“跨域”</p>
</blockquote>
</li>
<li><p><code>hash</code>当前地址栏<code>#</code>后面的东西</p>
<p><img src="https://pic.imgdb.cn/item/6146c6452ab3f51d9163af1b.png" srcset="/blog/img/loading.gif" lazyload alt="image-20210918113323589"></p>
<blockquote>
<p><strong>重点</strong>：这是非常重要的一个东西，后期的 SPA单页面开发当中，它是必不可少的，如<code>vue/react/angular</code>都必备这个点</p>
</blockquote>
</li>
<li><p><code>search</code>当前地址栏<code>?</code>后面的东西</p>
<p><img src="https://pic.imgdb.cn/item/6146c6452ab3f51d9163af1b.png" srcset="/blog/img/loading.gif" lazyload alt="image-20210918113820987"></p>
<blockquote>
<p><strong>超重点</strong>：这是一个超级重要的东西，因为后面的MVC开发框架里面要使用到这个，而SPA开发框架也使用到这个，它主要用于页面传值 ，客户端与到服务端的传值</p>
</blockquote>
</li>
<li><p><code>href</code>代表当前浏览器地址栏的网址，它可以取值，也可以赋值，如果赋值就是跳转新的页面</p>
</li>
<li><p><code>assign()</code>载入一个新的网址，用法与上面的<code>href</code>属性赋值是一样的</p>
</li>
<li><p><code>replace()</code>替换浏览器地址栏，网页会跳到新的地址</p>
</li>
<li><p><code>reload()</code>代表重新加载</p>
</li>
</ol>
<h3 id="replace方法与href的区别"><a href="#replace方法与href的区别" class="headerlink" title="replace方法与href的区别"></a>replace方法与href的区别</h3><p><code>replace()</code>方法与<code>href</code>属性赋值得可以跳转页面，但是它们是有本质的区别的，href是直接直接将一个新的地址入栈，而<code>replace</code>是替换的操作</p>
<p><strong>href直接赋值的操作</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-comment">//默认网页：http://127.0.0.1:5500/01location对象.html</span><br>location.href = <span class="hljs-string">&quot;https://www.baidu.com&quot;</span>;	<span class="hljs-comment">//第一次跳转</span><br>location.href = <span class="hljs-string">&quot;https://www.qq.com&quot;</span>;       <span class="hljs-comment">//第二次跳转</span><br></code></pre></td></tr></table></figure>

<p><img src="https://pic.imgdb.cn/item/6146c6802ab3f51d916410c3.png" srcset="/blog/img/loading.gif" lazyload alt="image-20210918121408001"></p>
<p>上面的图片就是href的赋值跳转页面的操作过程，它是直接入栈操作的</p>
<p><strong>replace()方法的操作</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-comment">//默认网页：http://127.0.0.1:5500/01location对象.html</span><br>location.href =<span class="hljs-string">&quot;https://www.baidu.com&quot;</span>;<br>location.replace(<span class="hljs-string">&quot;https://www.qq.com&quot;</span>);<br></code></pre></td></tr></table></figure>

<p><img src="https://pic.imgdb.cn/item/6146c6932ab3f51d9164336f.png" srcset="/blog/img/loading.gif" lazyload alt="image-20210918120336567"></p>
<p>这个时候我们点击后退的时候，会去哪个页面？</p>
<p>这个时候我们看到，会直接跳到最初始的地址，百度的历史记录不存在了</p>
<h2 id="2-history"><a href="#2-history" class="headerlink" title="2.history"></a>2.history</h2><p>这个对象用于访问当前浏览器的历史记录</p>
<ol>
<li><code>length</code>当前历史记录里面有几条数据</li>
<li><code>back()</code>历史记录当中后退一步，相当于浏览器的后退按钮操作</li>
<li><code>forward()</code>历史记录当中前进一步，相当于浏览器的前进按钮操作</li>
<li><code>go(step)</code>，如果<code>step</code>是正数就代表前进操作，如果<code>step</code>是负数就代表后退操作</li>
</ol>
<h2 id="3-window"><a href="#3-window" class="headerlink" title="3.window"></a>3.window</h2><p>widnow应该是我们浏览器当中的全局对象，在这个对象下面有一些方法我们先了解一下</p>
<ol>
<li><p><code>alert()</code>弹出一个对话框，它是线程阻塞的【线程阻塞就是阻止后面的代码运行，阻止页面的加载】</p>
</li>
<li><p><code>confirm()</code>弹出一个询问框，点击确定返回<code>true</code>，点击取消返回<code>false</code>，它也是线程阻塞的]</p>
</li>
<li><p><code>prompt()</code>弹出一个内容输入框，点击确定返回输入的内容，点击取消返回<code>null</code></p>
</li>
<li><p><code>open(url,target?,features?)</code>打开一个新的页面，新的页面称之为子页面</p>
<p>第一个参数代表要打开的网页的网址</p>
<p>第二个参数代表要打开的网页的方式，有<code>_self,_blank,_top,_parent,frameName</code>等</p>
<p>第三个参数代表打开新窗体的行为样式，如<code>width=200,height=400,left=200,too=300</code>等</p>
<p><img src="https://pic.imgdb.cn/item/6146c6f52ab3f51d9164dc80.png" srcset="/blog/img/loading.gif" lazyload alt="image-20210918142607000"></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs javascript"> <span class="hljs-comment">//跳到b页面</span><br><span class="hljs-comment">// location.href = &quot;b.html&quot;;</span><br><span class="hljs-comment">// location.assign(&quot;b.html&quot;);</span><br><span class="hljs-comment">// location.replace(&quot;b.html&quot;);</span><br><span class="hljs-comment">// ------------------------</span><br><span class="hljs-comment">// open(&quot;b.html&quot;,&quot;_blank&quot;);</span><br><span class="hljs-comment">// open(&quot;b.html&quot;, &quot;_self&quot;);</span><br><span class="hljs-comment">// open(&quot;b.html&quot;, &quot;_blank&quot;, &quot;width=200px,height=400px,left=300px,top=200px&quot;);</span><br></code></pre></td></tr></table></figure>
</li>
<li><p><code>close()</code>关闭当前页面</p>
</li>
</ol>
<h2 id="4-父子页面"><a href="#4-父子页面" class="headerlink" title="4.父子页面"></a>4.父子页面</h2><p>上面就是<code>window</code>对象下面经常使用到的方法，其实有一个方法一定要注意就是<code>open()</code>，这个方法可以打开一个新的页面，如<code>a.html</code>通过 open 打开<code>b.html</code>，则b页面就是a页面的子级页面</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">var</span> childWindow = open(<span class="hljs-string">&quot;4.a页面.html&quot;</span>, <span class="hljs-string">&quot;_blank&quot;</span>,<span class="hljs-string">&quot;width:400px,height:200px,left:100px&quot;</span>);<br><span class="hljs-comment">//childWindow 是子窗口的window对象</span><br></code></pre></td></tr></table></figure>

<p><img src="https://pic.imgdb.cn/item/6146c76c2ab3f51d9165a642.png" srcset="/blog/img/loading.gif" lazyload alt="image-20210918143905833"></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs javascript">childWindow.document.querySelector(<span class="hljs-string">&quot;.title&quot;</span>).innerText = <span class="hljs-string">&quot;父页面在更改子页面的标题&quot;</span>;<br></code></pre></td></tr></table></figure>

<p><img src="https://pic.imgdb.cn/item/6146c8112ab3f51d9166a77d.png" srcset="/blog/img/loading.gif" lazyload></p>
<h3 id="postMessage跨页面消息传递"><a href="#postMessage跨页面消息传递" class="headerlink" title="postMessage跨页面消息传递"></a>postMessage跨页面消息传递</h3><hr>
<h2 id="5-navigator浏览器对象"><a href="#5-navigator浏览器对象" class="headerlink" title="5.navigator浏览器对象"></a>5.navigator浏览器对象</h2><p>navigator对象记录当前用户的浏览器信息，它可以返回浏览器的版本号，核心以及兼容性等信息，还可以实现定位，摄像头调取等相关操作</p>
<ol>
<li><p><code>appVersion</code>代表当前浏览器的核心及版本编号</p>
</li>
<li><p><code>platform</code>代表当前浏览器的运行平台</p>
</li>
<li><p><code>maxTouchPoints</code>代表当前浏览器的支持的最大屏幕触摸点数</p>
</li>
<li><p><code>userAgent</code>用户标识，这个标识在浏览器访问某一个具体页面的时候会直接传送到服务器</p>
</li>
<li><p><code>clipboard</code>浏览器的剪切板</p>
</li>
<li><p><code>geolocation</code>地址位置信息，通过它可以实现定位</p>
<p>它里面有一个 <code>getCurrentPosition</code> 的方法，可以实现浏览器的定 位，定位成功以后里面有两个属性 coords 以及 timestamp coords 代表定位成功以后的坐标信息 </p>
<ul>
<li>latitude 纬度 </li>
<li>longitude 经度 </li>
<li>accuracy 准确性 </li>
<li>speed 速度 </li>
<li>altitude 海拔高度 </li>
<li>altitudeAccuracy 海拔高度的准确性 </li>
<li>heading 指南针方向</li>
</ul>
</li>
<li><p><code>getUserMedia</code>获取用户的多媒体设备，我们之前通过这个方法来获取用户的摄像头</p>
</li>
</ol>
<p><strong>使用浏览器定位</strong></p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">&quot;button&quot;</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;btn1&quot;</span>&gt;</span>定位<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript"></span><br><span class="javascript">    <span class="hljs-keyword">var</span> btn1 = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">&quot;#btn1&quot;</span>);</span><br><span class="javascript">    btn1.onclick = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">event</span>) </span>&#123;</span><br><span class="javascript">        navigator.geolocation.getCurrentPosition(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">pos</span>) </span>&#123;</span><br><span class="javascript">            <span class="hljs-comment">//定位成功以后的回调</span></span><br><span class="javascript">            <span class="hljs-built_in">console</span>.log(pos);</span><br><span class="javascript">        &#125;, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">error</span>) </span>&#123;</span><br><span class="javascript">            <span class="hljs-comment">//定位失败以后的回调</span></span><br><span class="javascript">            <span class="hljs-built_in">console</span>.log(error);</span><br><span class="javascript">        &#125;);</span><br><span class="javascript">    &#125;</span><br><span class="javascript"></span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span><br></code></pre></td></tr></table></figure>

<p>当定位成功成后，打印的结果如下</p>
<p><img src="https://pic.imgdb.cn/item/6146c9802ab3f51d9168e52d.png" srcset="/blog/img/loading.gif" lazyload alt="image-20210918154017681"></p>
<blockquote>
<p>上面就是使用定位来演示的信息，我们一般在使用浏览器定位的时候不能使用谷歌，而要使用其它的浏览器</p>
</blockquote>
<h2 id="6-screen屏幕对象"><a href="#6-screen屏幕对象" class="headerlink" title="6.screen屏幕对象"></a>6.screen屏幕对象</h2><ol>
<li><code>availHeight</code>屏幕的可用高度</li>
<li><code>availWidth</code>屏幕的可用宽度</li>
<li><code>width/height</code>屏幕的原始宽度与高度</li>
<li><code>orientation</code>屏幕的方向信息</li>
</ol>
<blockquote>
<p>这个BOM对象在移动端使用得非常多，经常通过这个对象来获取手机的屏幕大小以及方向等信息</p>
</blockquote>
<hr>
<h2 id="7-localStorage本地存储"><a href="#7-localStorage本地存储" class="headerlink" title="7.localStorage本地存储"></a>7.localStorage本地存储</h2><p>locatStorage是指本地缓存 ，它可以将字符串的数据存储存在本地浏览器上面， 它是window下面的一个属性对象 </p>
<ol>
<li><code>setItem(key,value)</code>设置一个缓存 </li>
<li><code>getItem(key)</code>获取一个缓存</li>
<li><code>removeItem(key)</code>删除一个缓存</li>
<li><code>clear()</code>清除所有的缓存 </li>
</ol>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-comment">//设置缓存 </span><br><span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">&quot;userName&quot;</span>,<span class="hljs-string">&quot;标哥哥&quot;</span>);<br><span class="hljs-comment">//获取缓存的值</span><br><span class="hljs-keyword">var</span> str = <span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">&quot;userName&quot;</span>);<br><br><span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">&quot;age&quot;</span>,<span class="hljs-number">18</span>);<br><span class="hljs-comment">// 删某一项缓存</span><br><span class="hljs-built_in">localStorage</span>.removeItem(<span class="hljs-string">&quot;age&quot;</span>);<br><br><span class="hljs-comment">//清除缓存 </span><br><span class="hljs-built_in">localStorage</span>.clear();<br><br><span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">&quot;aaa&quot;</span>);		<span class="hljs-comment">//不存在，得到结果 null</span><br></code></pre></td></tr></table></figure>

<p><img src="https://pic.imgdb.cn/item/614d17752ab3f51d9151edc3.png" srcset="/blog/img/loading.gif" lazyload alt="image-20210922085146605"></p>
<p>缓存是以<code>localStorage</code>的对象存在的，所以它还有操作方式【以对象的表式来操作】</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">&quot;userName&quot;</span>, <span class="hljs-string">&quot;张三&quot;</span>);<br><br><span class="hljs-comment">//通过对象的属性的方式来操作</span><br><span class="hljs-built_in">localStorage</span>.age = <span class="hljs-number">18</span>;<br><span class="hljs-built_in">localStorage</span>.sex = <span class="hljs-string">&quot;男&quot;</span>;<br><br><span class="hljs-comment">//获取</span><br><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">localStorage</span>.userName);<br><br><span class="hljs-comment">//删除</span><br><span class="hljs-keyword">delete</span> <span class="hljs-built_in">localStorage</span>.age;<br><br>localStroage.aaa;   <span class="hljs-comment">//不存在，得到结果undefined</span><br></code></pre></td></tr></table></figure>

<p><strong>特点</strong></p>
<ol>
<li>localStorage是本地存储，如果你不主动删除，它会一直存在</li>
<li>localStorage是可以跨页面访问的，后期可以通过这个方式来实现跨页面传值</li>
<li>localStorage不可以跨域访问</li>
<li>localStorage不可以跨浏览器访问</li>
</ol>
<h2 id="8-sessionStorage会话存储"><a href="#8-sessionStorage会话存储" class="headerlink" title="8.sessionStorage会话存储"></a>8.sessionStorage会话存储</h2><p>在讲这个东西之前，要弄清楚什么是session。session是会话的意思，指浏览器到服务器之间的链接</p>
<img src="https://pic.imgdb.cn/item/614d17fd2ab3f51d91525840.png" srcset="/blog/img/loading.gif" lazyload style="zoom:80%;" />

<p>既然是中间的链接，则这个链接就可以能会断开，断开以会就会影响<code>session</code>，所以<code>sessionStorage</code>是基于这一条链接上面的存储</p>
<p>它与<code>lcoalStorage</code>的操作方法保持一致</p>
<p><img src="https://pic.imgdb.cn/item/614d182d2ab3f51d91527b6b.png" srcset="/blog/img/loading.gif" lazyload alt="image-20210922093845928"></p>
<ol>
<li><code>setItem(key,value)</code>设置一个缓存 </li>
<li><code>getItem(key)</code>根据一个键获取一个缓存值</li>
<li><code>removeItem(key)</code>根据一个键删除一个缓存</li>
<li><code>clear()</code>清除以后有的localStorage</li>
</ol>
<p>同时也要注意，它也支持对象操作属性的方式来进行</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs javascript">sessionStorage.studentAge = <span class="hljs-number">19</span>;						<span class="hljs-comment">//新增一个属性</span><br><span class="hljs-built_in">console</span>.log(sessionStorage.studentName);			<span class="hljs-comment">//获取属性值</span><br><span class="hljs-keyword">delete</span> sessionStorage.studentAge;					<span class="hljs-comment">//删除一个属性</span><br></code></pre></td></tr></table></figure>

<p><strong>特点</strong></p>
<ol>
<li><p><code>sessionStroage</code>在浏览器关闭会话中断的时候会自动销毁</p>
</li>
<li><p><code>sessionStorage</code>默认是不允许跨页面的，但是可以跨父子页面</p>
<p>通过<code>window.open()</code>打开的页面是可以互相访问的</p>
<p>通过<code>a</code>标签打开，但是<code>target=&quot;_self&quot;</code>打开的页面也是可以互相访问的</p>
</li>
<li><p><code>sessionStorage</code>不能跨域</p>
</li>
<li><p><code>sessionStorage</code>不能跨浏览器</p>
</li>
</ol>
<h2 id="9-JSON对象"><a href="#9-JSON对象" class="headerlink" title="9.JSON对象"></a>9.JSON对象</h2><blockquote>
<p>存在的问题，我们不能直接存储对象（直接存储后为[Object Object]）</p>
</blockquote>
<p>这个时候有一个技术就产生了，它是<code>JSON</code>，<a target="_blank" rel="noopener" href="https://baike.baidu.com/item/JSON">JSON</a>(<a target="_blank" rel="noopener" href="https://baike.baidu.com/item/JavaScript">JavaScript</a> Object Notation, JS 对象简谱) 是一种<strong>轻量级的数据交换格式</strong>。它基于 <a target="_blank" rel="noopener" href="https://baike.baidu.com/item/ECMAScript">ECMAScript</a> (欧洲计算机协会制定的js规范)的一个子集，采用完全独立于编程语言的<strong>文本格式</strong>来存储和表示数据。简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。 易于人阅读和编写，同时也易于机器解析和生成，并有效地提升网络传输效率。</p>
<p>说得通俗一点：JSON就是以字符串的形式去表示对象</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">var</span> obj = &#123;<br>    <span class="hljs-attr">userName</span>:<span class="hljs-string">&quot;张三&quot;</span>,<br>    <span class="hljs-attr">age</span>:<span class="hljs-number">18</span><br>&#125;<br><span class="hljs-comment">//如果使用字符串表示对象（JSON），如下操作</span><br><span class="hljs-keyword">var</span> str = <span class="hljs-string">&#x27;&#123;&quot;userName&quot;:&quot;张三&quot;,&quot;age&quot;:18&#125;&#x27;</span>;<br></code></pre></td></tr></table></figure>

<p>通过对比，我们可以发现，<code>JSON</code>主是将原来对象的属性名加了一个引号，然后在整个对象又加了一个引号变成了字符串</p>
<h3 id="JSON的序列化"><a href="#JSON的序列化" class="headerlink" title="JSON的序列化"></a>JSON的序列化</h3><p>将对象转换成字符串形式的表示我们称之为JSON序列化</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">var</span> obj = &#123;<br>    <span class="hljs-attr">userName</span>: <span class="hljs-string">&quot;张三&quot;</span>,<br>    <span class="hljs-attr">age</span>: <span class="hljs-number">18</span><br>&#125;<br><span class="hljs-comment">//上面是一个对象，把它序列化成字符串</span><br><span class="hljs-keyword">var</span> str = <span class="hljs-built_in">JSON</span>.stringify(obj);<br><br><span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">&quot;userInfo&quot;</span>,str);<br></code></pre></td></tr></table></figure>

<p>这个时候我们就将对象转换成了字符串，这个过程我们叫JSON序列化</p>
<p><code>JSON.stringify()</code>这就是一个对象序列化成JSON的方法，其实原理是在这个对象的内部调用了toJSON的方法</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">var</span> stu1 = &#123;<br>    <span class="hljs-attr">stuName</span>: <span class="hljs-string">&quot;张三&quot;</span>,<br>    <span class="hljs-attr">sex</span>: <span class="hljs-string">&quot;男&quot;</span><br>&#125;<br><br><span class="hljs-keyword">var</span> str1 = <span class="hljs-built_in">JSON</span>.stringify(stu1);<br><span class="hljs-built_in">console</span>.log(str1); <span class="hljs-comment">//&#x27;&#123;&quot;stuName&quot;:&quot;张三&quot;,&quot;sex&quot;:&quot;男&quot;&#125;&#x27;</span><br><br><br><span class="hljs-keyword">var</span> stu2 = &#123;<br>    <span class="hljs-attr">stuName</span>: <span class="hljs-string">&quot;李四&quot;</span>,<br>    <span class="hljs-attr">sex</span>: <span class="hljs-string">&quot;男&quot;</span>,<br>    <span class="hljs-attr">toJSON</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>&#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;标哥哥&quot;</span>;<br>    &#125;<br>&#125;<br><br><span class="hljs-keyword">var</span> str2 = <span class="hljs-built_in">JSON</span>.stringify(stu2);<br><span class="hljs-built_in">console</span>.log(str2); <span class="hljs-comment">//&quot;标哥哥&quot;</span><br></code></pre></td></tr></table></figure>

<blockquote>
<p>代码分析：</p>
<ol>
<li>在第一次操作的时候，对象内部没有<code>toJSON</code>这个方法，所以正常的转换成了JSON字符串</li>
<li>在第二次操作的时候，对象内部有了<code>toJSON</code>这个方法，在使用<code>JSON.stringify()</code>进行序列化的时候，会优先调用<code>toJSON</code>方法的结果，所以得到的是一个“标哥哥”的字符串</li>
</ol>
</blockquote>
<h3 id="JSON的反序列化"><a href="#JSON的反序列化" class="headerlink" title="JSON的反序列化"></a>JSON的反序列化</h3><p>将JSON字符串转换成对象这个过程，我们叫<strong>反序列化</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs javascript"> <span class="hljs-comment">//&#x27;&#123;&quot;userName&quot;:&quot;张三&quot;,&quot;age&quot;:18&#125;&#x27;</span><br><span class="hljs-keyword">var</span> str = <span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">&quot;userInfo&quot;</span>);<br><span class="hljs-built_in">console</span>.log(str);<br><br><span class="hljs-comment">//将JSON字符串转换对象</span><br><span class="hljs-keyword">var</span> obj = <span class="hljs-built_in">JSON</span>.parse(str);<br><span class="hljs-built_in">console</span>.log(obj);<br></code></pre></td></tr></table></figure>

<hr>
<h2 id="10-document对象"><a href="#10-document对象" class="headerlink" title="10.document对象"></a>10.document对象</h2><p>document对象指的是当前网页，综是<code>window</code>对象下面的一个属性对象，叫<code>window.document</code></p>
<ol>
<li><code>documentElement</code>指当前网页的<code>html</code>元素</li>
<li><code>write()</code>在网页上面打印一段文字，如果不是同一个文档流，会清除之前的网页内容</li>
<li><code>writeln()</code>在网页上面打印一段文字，会显示一个空格位</li>
</ol>
<h2 id="11-cookie"><a href="#11-cookie" class="headerlink" title="11.cookie"></a>11.cookie</h2><p>cookie它也用于存储数据的，与上面所学习的<code>localStorage</code>及<code>sessionStorage</code>是一样的功能，但是原理完成不同</p>
<p><strong>区别点：</strong></p>
<ol>
<li><p>localStorage与sessionStorage是window下面的属性对象，而cookie则是document下面的属性</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-built_in">window</span>.sessionStorage;<br><span class="hljs-built_in">window</span>.localStorage;<br><span class="hljs-built_in">window</span>.document.cookie;<br></code></pre></td></tr></table></figure>
</li>
<li><p>localStorage与sessionStorage是基于对象的键值对存储，cookie则是以字符串的形式存储</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-built_in">document</span>.cookie;<br><span class="hljs-string">&quot;p_h5_u=42D46F6E-4E9E-4D3C-9436-C6359243272F; userName=&#x27;bgg&#x27;&quot;</span><br></code></pre></td></tr></table></figure>
</li>
<li><p>localStorage与sessionStorage存储在浏览器上面的，而cookie是存储在<code>document</code>网页文档上面，网页文档会随机浏览器请求到达服务器，而随着服务器的响应返回浏览器</p>
<p><img src="https://pic.imgdb.cn/item/614d1a162ab3f51d915405f6.png" srcset="/blog/img/loading.gif" lazyload></p>
</li>
</ol>
<p>通过上面的对比我们可以发现cookie操作方式与之前的storage的操作方式是不一样的， 它非常复杂，很麻烦，所以们要学习它的操作方式</p>
<h3 id="cookie的赋值操作"><a href="#cookie的赋值操作" class="headerlink" title="cookie的赋值操作"></a>cookie的赋值操作</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-built_in">document</span>.cookie = <span class="hljs-string">&quot;userName=bgg&quot;</span>;<br></code></pre></td></tr></table></figure>

<p><img src="https://pic.imgdb.cn/item/614d1a6a2ab3f51d91544b3b.png" srcset="/blog/img/loading.gif" lazyload alt="image-20210922113328828"></p>
<ol>
<li>名称是cookie的名称</li>
<li>值代表cookie的值</li>
<li>Domain代表主机地址</li>
<li>Path代表cookie设置的路径</li>
<li>Expires代表过期时间，过期时间一到，cookie自动删除，这里的传话指的是session，一旦断开就自动消失。但是要注意，这里的过期时间是以0时区的时间为标准</li>
</ol>
<p><strong>设置cookie的过期时间</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">var</span> d = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-string">&quot;2021-9-22 11:44:00&quot;</span>);<br><span class="hljs-built_in">document</span>.cookie = <span class="hljs-string">&quot;userName = bgg;Expires=&quot;</span>+d.toGMTString();<br></code></pre></td></tr></table></figure>

<p><strong>设置cookie的路径path</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-comment">//http://127.0.0.1:5500/13cookie.html</span><br><span class="hljs-built_in">document</span>.cookie = <span class="hljs-string">&quot;userName = bgg;Expires=&quot;</span>+<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-string">&quot;2021-10-1&quot;</span>).toGMTString();<br></code></pre></td></tr></table></figure>

<p><img src="https://pic.imgdb.cn/item/614d1a8e2ab3f51d915464d8.png" srcset="/blog/img/loading.gif" lazyload alt="image-20210922115144993"></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-comment">//http://127.0.0.1:5500/aaa/14cookie.html</span><br><span class="hljs-built_in">document</span>.cookie = <span class="hljs-string">&quot;age = 18;Expires=&quot;</span>+<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-string">&quot;2021-10-1&quot;</span>).toGMTString();<br></code></pre></td></tr></table></figure>

<p><img src="https://pic.imgdb.cn/item/614d1aaa2ab3f51d915478c9.png" srcset="/blog/img/loading.gif" lazyload alt="image-20210922115217554"></p>
<blockquote>
<p>这个时候我们发现，父级路径 的<code>/</code>根路径 访问不了子级路径的cookie,而子级路径<code>/aaa</code>是可以访问根路径<code>/</code>的</p>
</blockquote>
<p>我们也可以在子级页面设置<code>cookie</code>时候设置为根路径<code>/</code>，如下</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-built_in">document</span>.cookie = <span class="hljs-string">&quot;sex = 男;Expires=&quot;</span>+<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-string">&quot;2021-10-1&quot;</span>).toGMTString()+<span class="hljs-string">&quot;;path=/&quot;</span><br></code></pre></td></tr></table></figure>

<p><img src="https://pic.imgdb.cn/item/614d1ace2ab3f51d9154940b.png" srcset="/blog/img/loading.gif" lazyload alt="image-20210922115438401"></p>
<p><strong>赋值操作总结</strong></p>
<ol>
<li><p>cookie是document对象的一个属性，所以操作是<code>document.cookie</code>来进行</p>
</li>
<li><p>cookie是可以跨页面访问的，但是可以通过路径path隔开，父级路径访问不了子级路径的cookie，而子级路径可以访问父级路径的cookie</p>
</li>
<li><p>cookie不能跨域</p>
</li>
<li><p>赋值使用如下语法格式</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-built_in">document</span>.cookie = <span class="hljs-string">&quot;cookie名=cookie值;Expires = 过期GMT时间;path = 路径&quot;</span><br></code></pre></td></tr></table></figure>

</li>
</ol>
<h3 id="cookie的取值操作"><a href="#cookie的取值操作" class="headerlink" title="cookie的取值操作"></a>cookie的取值操作</h3><p>所有的cookie值都保存在<code>document.cookie</code>的这个下面，如下</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-built_in">document</span>.cookie;			<span class="hljs-comment">//&#x27;userName=标哥哥; age=18&#x27;</span><br></code></pre></td></tr></table></figure>

<p><strong>第一种方式：使用字符串转数组的方法</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-comment">//例如，取userName</span><br><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getCookieValue</span>(<span class="hljs-params">cookieName</span>) </span>&#123;<br>    <span class="hljs-keyword">var</span> arr = <span class="hljs-built_in">document</span>.cookie.split(<span class="hljs-string">&quot;;&quot;</span>); <span class="hljs-comment">// [&#x27;userName=标哥哥&#x27;, &#x27; age=18&#x27;]</span><br>    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; arr.length; i++) &#123;<br>        <span class="hljs-keyword">var</span> item = arr[i];<br>        <span class="hljs-keyword">var</span> temp = item.split(<span class="hljs-string">&quot;=&quot;</span>); <span class="hljs-comment">// [&quot;userName&quot;,&quot;标哥哥&quot;];</span><br>        <span class="hljs-keyword">if</span> (temp[<span class="hljs-number">0</span>].trim() == cookieName) &#123;<br>            <span class="hljs-keyword">return</span> temp[<span class="hljs-number">1</span>];<br>        &#125;<br>    &#125;<br>&#125;<br><span class="hljs-keyword">var</span> userName = getCookieValue(<span class="hljs-string">&quot;userName&quot;</span>);<br></code></pre></td></tr></table></figure>

<p><strong>第二种方式：使用正则表达式的方法</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getCookieValue</span>(<span class="hljs-params">cookieName</span>) </span>&#123;<br>    <span class="hljs-keyword">var</span> str = <span class="hljs-built_in">document</span>.cookie; <span class="hljs-comment">//&#x27;userName=标哥哥; age=18&#x27;</span><br>    str += <span class="hljs-string">&quot;;&quot;</span>; <span class="hljs-comment">//在最后面加一个分号是为了方便我们正简单的使用正则表达式去提取</span><br>    <span class="hljs-comment">//正则表达式如果需要拼接变量，我们就使用new RegExp这种方式来完成</span><br>    <span class="hljs-keyword">var</span> reg = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(<span class="hljs-string">&quot;(?&lt;=&quot;</span> + cookieName + <span class="hljs-string">&quot;=).*?(?=;)&quot;</span>, <span class="hljs-string">&quot;g&quot;</span>);<br>    <span class="hljs-keyword">var</span> arr = str.match(reg);<br>    <span class="hljs-keyword">return</span> arr ? arr[<span class="hljs-number">0</span>] : <span class="hljs-literal">undefined</span>;<br>&#125;<br><br><span class="hljs-keyword">var</span> userName = getCookieValue(<span class="hljs-string">&quot;userName&quot;</span>);<br></code></pre></td></tr></table></figure>

<h3 id="cookie的删除操作"><a href="#cookie的删除操作" class="headerlink" title="cookie的删除操作"></a>cookie的删除操作</h3><p>cookie是根据过期时间来进行删除的，所以如果想删除一个cookie，只需要设置它的过期时间为<code>1970-1-1</code>即可</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">deleteCookie</span>(<span class="hljs-params">cookieName</span>) </span>&#123;<br>    <span class="hljs-keyword">var</span> d = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-string">&quot;1970-1-1&quot;</span>);<br>    <span class="hljs-comment">//相当于重新设置了一遍cookie，只是把cookie的过期时间过了</span><br>    <span class="hljs-comment">//过期以后cookie会自动删除</span><br>    <span class="hljs-built_in">document</span>.cookie = cookieName + <span class="hljs-string">&quot; = ;Expires = &quot;</span> + d.toGMTString();<br>&#125;<br><br>deleteCookie(<span class="hljs-string">&quot;age&quot;</span>);<br></code></pre></td></tr></table></figure>

<h3 id="cookie操作的封装"><a href="#cookie操作的封装" class="headerlink" title="cookie操作的封装"></a>cookie操作的封装</h3><p>在上面的学习当中，我们已经编写了几个方法，用于cookie的常用操作。现在我们通过面向对象将这些方法进行封装，以方便后期的使用</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">var</span> cookieHelper = &#123;<br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@description </span>设置cookie</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param <span class="hljs-type">&#123;string&#125;</span> </span>cookieName  cookie名称</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param <span class="hljs-type">&#123;string&#125;</span> </span>cookieValue  cookie的值</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param <span class="hljs-type">&#123;string&#125;</span> </span>expires     过期时间</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param <span class="hljs-type">&#123;string&#125;</span> </span>path         路径</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-attr">setCookie</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">cookieName, cookieValue, expires, path</span>) </span>&#123;<br>        <span class="hljs-keyword">var</span> cookieStr = cookieName + <span class="hljs-string">&quot; = &quot;</span> + cookieValue;<br>        <span class="hljs-keyword">if</span> (expires) &#123;<br>            cookieStr += <span class="hljs-string">&quot;;Expires = &quot;</span> + expires;<br>        &#125;<br>        <span class="hljs-keyword">if</span> (path) &#123;<br>            cookieStr += <span class="hljs-string">&quot;;path = &quot;</span> + path;<br>        &#125;<br>        <span class="hljs-built_in">document</span>.cookie = cookieStr;<br>    &#125;,<br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@description </span>根据cookie的名称获取cookie的值</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param <span class="hljs-type">&#123;string&#125;</span> </span>cookieName cookie名称 </span><br><span class="hljs-comment">     * <span class="hljs-doctag">@returns <span class="hljs-type">&#123;any&#125;</span> </span>返回获取到的cookie的值，如果获取不到就是undefined </span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-attr">getCookieValue</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">cookieName</span>) </span>&#123;<br>        <span class="hljs-keyword">var</span> str = <span class="hljs-built_in">document</span>.cookie;<br>        str += <span class="hljs-string">&quot;;&quot;</span>;<br>        <span class="hljs-keyword">var</span> reg = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(<span class="hljs-string">&quot;(?&lt;=&quot;</span> + cookieName + <span class="hljs-string">&quot;=).*?(?=;)&quot;</span>, <span class="hljs-string">&quot;g&quot;</span>);<br>        <span class="hljs-keyword">var</span> arr = str.match(reg);<br>        <span class="hljs-keyword">return</span> arr ? arr[<span class="hljs-number">0</span>] : <span class="hljs-literal">undefined</span>;<br>    &#125;,<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@description </span>根据cookie的名称删除当前cookie项</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param <span class="hljs-type">&#123;string&#125;</span> </span>cookieName cookie名称</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-attr">deleteCookie</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">cookieName</span>) </span>&#123;<br>        <span class="hljs-built_in">this</span>.setCookie(cookieName, <span class="hljs-string">&quot;&quot;</span>, <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-string">&quot;1970-1-1&quot;</span>).toGMTString());<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<hr>
<h3 id=""><a href="#" class="headerlink" title=""></a></h3><h2 id="12-URL对象"><a href="#12-URL对象" class="headerlink" title="12.URL对象"></a>12.URL对象</h2><p>在WWW上，每一信息资源都有统一的且在网上唯一的<a target="_blank" rel="noopener" href="https://baike.baidu.com/item/%E5%9C%B0%E5%9D%80/80420">地址</a>，该地址就叫URL（Uniform Resource Locator,统一资源定位器），它是WWW的统一资源定位标志，就是指网络地址，也简称网址。</p>
<p>URL由三部分组成：资源类型、存放资源的主机域名、资源文件名。</p>
<p>也可认为由4部分组成：协议、主机、端口、路径</p>
<p>URL的一般语法格式为：</p>
<p>(带方括号[]的为可选项)：</p>
<p><code>protocol :// hostname[:port] / path / [;parameters][?query]#fragment</code></p>
<p>URL对象与我们的location对象非常相似，但是比location对象更加高级一点</p>
<p><img src="https://pic.imgdb.cn/item/614d1be92ab3f51d915569ba.png" srcset="/blog/img/loading.gif" lazyload alt="image-20210922162544278"></p>
<p>一个URL应该是包含上面的几个部分的，URL对象可以帮助我们快速的解析网址的字符串</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">var</span> str = <span class="hljs-string">&quot;http://www.xxx.com:8080/abc/1.html?action=getAllList&amp;age=18#box&quot;</span>;<br><span class="hljs-keyword">var</span> u = <span class="hljs-keyword">new</span> URL(str);<br><span class="hljs-built_in">console</span>.log(u);<br></code></pre></td></tr></table></figure>

<p><img src="https://pic.imgdb.cn/item/614d1c092ab3f51d91558024.png" srcset="/blog/img/loading.gif" lazyload alt="image-20210922154304275"></p>
<p>上图就是URL对象的详细，它把之前是的str字符串变成一个网址对象，在这个对象里面我们可以清楚的看到它的相关信息（这些信息与location非常相似）</p>
<h3 id="URLSearchParams对象"><a href="#URLSearchParams对象" class="headerlink" title="URLSearchParams对象"></a>URLSearchParams对象</h3><p>在上面的对象里面，我们看到了一个属性叫<code>searchParams</code>，它是一个<code>URLSearchParams</code>对象，对象详细信息如下</p>
<p><img src="https://pic.imgdb.cn/item/614d1c3a2ab3f51d9155ae2b.png" srcset="/blog/img/loading.gif" lazyload alt="image-20210922154603131"></p>
<p>这样对象主要用于URL地址栏传值，与这们之前学习的location三大属性search保持一致，都是超级重要的东西。这个对象主要用于设置URL地址里面的<code>search</code></p>
<p><strong>案例：通过search来实现页面的伟值</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-comment">//02login.html页面</span><br><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">checkLogin</span>(<span class="hljs-params"></span>) </span>&#123;<br>    <span class="hljs-keyword">var</span> userName = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">&quot;#userName&quot;</span>).value;<br>    <span class="hljs-keyword">var</span> pwd = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">&quot;#pwd&quot;</span>).value;<br>    <span class="hljs-built_in">window</span>.open(<span class="hljs-string">&quot;./03admin.html?aaa=&quot;</span> + userName + <span class="hljs-string">&quot;&amp;bbb=&quot;</span> + pwd);<br>&#125;<br><br><span class="hljs-comment">//03admin.html页面</span><br><span class="hljs-comment">//http://192.168.1.254:5500/03admin.html?aaa=biaogege&amp;bbb=123456</span><br><span class="hljs-keyword">var</span> u = <span class="hljs-keyword">new</span> URL(location.href);<br><span class="hljs-keyword">var</span> aaa = u.searchParams.get(<span class="hljs-string">&quot;aaa&quot;</span>);<br><span class="hljs-keyword">var</span> bbb = u.searchParams.get(<span class="hljs-string">&quot;bbb&quot;</span>);<br><span class="hljs-keyword">var</span> zzz = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">&quot;#zzz&quot;</span>);<br>zzz.innerText = <span class="hljs-string">&quot;你之前的登陆的用户名是：&quot;</span> + aaa + <span class="hljs-string">&quot;,你的密码是：&quot;</span> + bbb;<br></code></pre></td></tr></table></figure>

<blockquote>
<p>代码分析：</p>
<ol>
<li>在02login.html的这个页面里面，我们在跳转页面的时候，在这个页面的后面追加了一个<code>search</code>的值，这并不影响页面跳转</li>
<li>在03admin.html的页面里面，我们将location.href的地址转变成了URL对象，然后再通过<code>URL</code>对象的<code>searchParams</code>来操作<code>search</code>后面传递过来的参数</li>
</ol>
</blockquote>
<h3 id="URL编码与解码"><a href="#URL编码与解码" class="headerlink" title="URL编码与解码"></a>URL编码与解码</h3><p>当网页地址里面如果有中文的时候，浏览器在操作的时候会自动的进行编码，如下所示</p>
<p><strong>原网址</strong></p>
<figure class="highlight apache"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs apache"><span class="hljs-attribute">http</span>://<span class="hljs-number">127.0.0.1:5500</span>/<span class="hljs-number">04</span>url对象练习.html<br></code></pre></td></tr></table></figure>

<p><strong>编码以后</strong></p>
<figure class="highlight apache"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs apache"><span class="hljs-attribute">http</span>://<span class="hljs-number">127.0.0.1:5500</span>/<span class="hljs-number">04</span>url%E<span class="hljs-number">5</span>%AF%B<span class="hljs-number">9</span>%E<span class="hljs-number">8</span>%B<span class="hljs-number">1</span>%A<span class="hljs-number">1</span>%E<span class="hljs-number">7</span>%BB%<span class="hljs-number">83</span>%E<span class="hljs-number">4</span>%B<span class="hljs-number">9</span>%A<span class="hljs-number">0</span>.html<br></code></pre></td></tr></table></figure>

<ol>
<li><code>encodeURIComponent()</code>对字符串进行URI编码</li>
<li><code>decodeURIComponent()</code>对字符串进行URI解码</li>
</ol>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">var</span> str = <span class="hljs-string">&quot;大家好，我是标哥哥&quot;</span>;<br><span class="hljs-comment">//编码</span><br><span class="hljs-keyword">var</span> str1 = <span class="hljs-built_in">encodeURIComponent</span>(str);<br><span class="hljs-comment">//%E5%A4%A7%E5%AE%B6%E5%A5%BD%EF%BC%8C%E6%88%91%E6%98%AF%E6%A0%87%E5%93%A5%E5%93%A5</span><br><span class="hljs-built_in">console</span>.log(str1);<br><br><span class="hljs-comment">//------------------------------</span><br><br><span class="hljs-keyword">var</span> str2 = <span class="hljs-string">&quot;%E5%A4%A7%E5%AE%B6%E5%A5%BD%EF%BC%8C%E6%88%91%E6%98%AF%E6%A0%87%E5%93%A5%E5%93%A5&quot;</span>;<br><span class="hljs-comment">//解码</span><br><span class="hljs-keyword">var</span> str3 = <span class="hljs-built_in">decodeURIComponent</span>(str2);<br><span class="hljs-built_in">console</span>.log(str3);<br></code></pre></td></tr></table></figure>

<hr>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/blog/categories/%E5%89%8D%E7%AB%AF%E7%AC%94%E8%AE%B0/">前端笔记</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/blog/tags/JavaScript/">JavaScript</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/blog/2021/10/06/JQuery%E7%AC%94%E8%AE%B0/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">JQuery笔记</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/blog/2021/09/27/JavaScript%E7%AC%94%E8%AE%B0-DOM/">
                        <span class="hidden-mobile">JavaScript笔记-DOM</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
  </div>
  

  

  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.min.js" ></script>
<script  src="/blog/js/events.js" ></script>
<script  src="/blog/js/plugins.js" ></script>

<!-- Plugins -->


  
    <script  src="/blog/js/img-lazyload.js" ></script>
  



  



  <script  src="https://cdn.jsdelivr.net/npm/tocbot@4.12.3/dist/tocbot.min.js" ></script>



  <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js" ></script>



  <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4.3.1/anchor.min.js" ></script>



  <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2.0.8/dist/clipboard.min.js" ></script>



  <script  src="/blog/js/local-search.js" ></script>






  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2.0.12/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
      typing(title)
      
    })(window, document);
  </script>









  <script  src="https://cdn.jsdelivr.net/npm/mermaid@8.10.1/dist/mermaid.min.js" ></script>
  <script>
    if (window.mermaid) {
      mermaid.initialize({"theme":"default"});
    }
  </script>







<!-- 主题的启动项 保持在最底部 -->
<script  src="/blog/js/boot.js" ></script>


</body>
</html>
